#include "language.h"
#include "parser.h"
#include <iostream>
#include <fstream>
#include <map>

using namespace std;
using namespace syntax_analysis;

int main( int argc, char** argv )
{
	static char buf[10240000];
	string cmd;
	string file;
	string path="";
	string name;
	parser *parse = new parser();
	language *lang;
	map<string,language*> lang_set;

	do 
	{
		cin >> cmd;
		if( cmd == "cl" )
		{
			cin >> file;
			file = path + file;
			ifstream fs( file.c_str() );
			if( fs.is_open() )
			{
				long pos = fs.tellg();
				fs.seekg( 0, ios::beg );
				pos = fs.tellg();
				
				memset( buf, 0, sizeof(buf) );
				fs.read( buf, 10240000 );
				lang = parse->do_parser( buf );
				if( lang != NULL )
				{
					map<string,language*>::iterator i;
					i = lang_set.find( lang->get_name() );
					if( i != lang_set.end() )
					{
						cout << "language [" << lang->get_name() << "] already existed!" << endl;
						cout << "replaced by new one!" << endl;
						delete i->second;
						lang_set[lang->get_name()] = lang;
					}
					else
					{
						cout << "done [" << lang->get_name() << "]" << endl;
						lang_set[lang->get_name()] = lang;
					}
				}
			}
			else
			{
				cout << "failed to open " << file << endl;
			}
		}
		else if( cmd == "parse" )
		{
			cin >> name;
			cin >> file;
			file = path + file;
			ifstream fs( file.c_str() );

			if( fs.is_open() )
			{
				memset( buf, 0, sizeof(buf) );
				fs.read( buf, 10240000 );

				map<string,language*>::iterator i;
				i = lang_set.find( name );
				if( i != lang_set.end() )
				{
					lang = i->second;
					if( lang->parse( buf ) )
						cout << "passed!" << endl;
					else
						cout << "not excepted!" << endl;
				}
				else
				{
					cout << "language not found: " << name << endl;
				}
			}
			else
			{
				cout << "failed to open file " << file << endl;
			}
		}
		else if( cmd == "print" )
		{
			cin >> name;
			map<string,language*>::iterator i;
			i = lang_set.find( name );
			if( i != lang_set.end() )
				cout << i->second->to_string() << endl;
			else
				cout << "language not found: " << name << endl;
		}
		else if( cmd == "set_path" )
		{
			cin >> path;
		}
		else if( cmd == "list_lang" )
		{
			map<string,language*>::iterator i;
			for( i = lang_set.begin(); i != lang_set.end(); ++i )
				cout << "    " << i->first << endl;
		}

	} while( cmd != "exit" );

	return 0;
}
